#!/usr/bin/env python2
# coding: utf-8

"""
    author: yao wei
    contact: njustyw@gmail.com
    file: image_test.py
    time: 24/3/2017
"""

import unittest
from zstack.controller import image
from zstack import Client

ADMIN_USERNAME = 'admin'
ADMIN_PASSWORD = 'password'
ZSTACK_API_URL = 'http://192.168.1.115:8080/zstack/api'
IMAGE_UUID = '8fb4cffd2dc142ef9c3204ed32d88656'
BACKUP_STORAGE_UUID = '66cad101d56f430b9c9a017545ce7f1a'


class TestImage(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.client = Client(ADMIN_USERNAME, ADMIN_PASSWORD, ZSTACK_API_URL)
        cls.client.login()

    def test_image_category(self):
        """更新镜像标签"""
        image.updata_image_category(self.client, IMAGE_UUID, ['123', 'ABC'])
        categories = image.query_image_property(self.client, IMAGE_UUID, key='categories')
        self.assertEqual(categories, ['123', 'ABC'])

        image.updata_image_category(self.client, IMAGE_UUID, ['456'])
        categories = image.query_image_property(self.client, IMAGE_UUID, key='categories')
        self.assertEqual(categories, ['456'])

    def test_create_update_delete_query_image(self):
        """新增镜像/编辑/删除镜像"""
        # 新增镜像
        new = image.add_image(self.client, 'py_test01', 'py_description01', 'RootVolumeTemplate',
                              'Linux', 'http://192.168.1.105/cirros-0.3.3-x86_64-disk.img',
                              [BACKUP_STORAGE_UUID], 'qcow2')
        self.assertEqual(new['description'], 'py_description01')
        self.assertEqual(new['name'], 'py_test01')
        self.assertEqual(new['format'], 'qcow2')
        self.assertEqual(new['platform'], 'Linux')

        # 在镜像列表中查询该镜像
        self.assertIn(new['uuid'], [im.get('uuid') for im in image.query_image(self.client)])

        # 编辑该镜像
        new = image.update_image(self.client, new['uuid'], u'新的镜像', u'新的描述')
        self.assertEqual(new['name'], u'新的镜像')
        self.assertEqual(new['description'], u'新的描述')

        # 查询该镜像
        image2 = image.query_image_by_uuid(self.client, new['uuid'])
        self.assertTrue(image2 is not None)

        # 查询不存在的镜像
        image3 = image.query_image_by_uuid(self.client, 'not exist')
        self.assertTrue(image3 == [])

        # 删除该镜像
        image.delete_image(self.client, new['uuid'])
        self.assertNotIn(new['uuid'], [im.get('uuid') for im in image.query_image(self.client)])


if __name__ == '__main__':
    unittest.main()
